""" 
路由调试工具
"""
from flask import Blueprint, jsonify, current_app

# 创建蓝图
routes_bp = Blueprint('routes', __name__, url_prefix='/api/debug')

@routes_bp.route('/routes', methods=['GET'])
def list_routes():
    """打印所有路由信息"""
    try:
        routes_info = []
        
        # 遍历所有URL规则
        for rule in current_app.url_map.iter_rules():
            route_info = {
                'endpoint': rule.endpoint,
                'methods': list(rule.methods - {'HEAD', 'OPTIONS'}),  # 排除自动添加的方法
                'path': rule.rule,
                'subdomain': rule.subdomain or '',
                'strict_slashes': rule.strict_slashes
            }
            routes_info.append(route_info)
        
        # 按路径排序
        routes_info.sort(key=lambda x: x['path'])
        
        return jsonify({
            'code': 200,
            'message': '获取路由列表成功',
            'data': {
                'total': len(routes_info),
                'routes': routes_info
            }
        })
        
    except Exception as e:
        return jsonify({
            'code': 500,
            'message': f'获取路由列表失败: {str(e)}'
        }), 500


@routes_bp.route('/endpoints', methods=['GET'])
def list_endpoints():
    """获取所有端点信息（按蓝图分组）"""
    try:
        endpoints_by_blueprint = {}
        
        for rule in current_app.url_map.iter_rules():
            # 解析蓝图名称
            blueprint_name = 'main'  # 默认蓝图
            if '.' in rule.endpoint:
                blueprint_name = rule.endpoint.split('.')[0]
            
            if blueprint_name not in endpoints_by_blueprint:
                endpoints_by_blueprint[blueprint_name] = []
            
            endpoint_info = {
                'endpoint': rule.endpoint,
                'methods': list(rule.methods - {'HEAD', 'OPTIONS'}),
                'path': rule.rule
            }
            endpoints_by_blueprint[blueprint_name].append(endpoint_info)
        
        # 对每个蓝图内的路由进行排序
        for blueprint in endpoints_by_blueprint:
            endpoints_by_blueprint[blueprint].sort(key=lambda x: x['path'])
        
        return jsonify({
            'code': 200,
            'message': '获取端点列表成功',
            'data': endpoints_by_blueprint
        })
        
    except Exception as e:
        return jsonify({
            'code': 500,
            'message': f'获取端点列表失败: {str(e)}'
        }), 500